const { default: axios } = require("axios");
const { JSDOM } = require("jsdom");
const fs = require("fs");
const path = require("path");

const domain = "http://10.10.1.33:8090";
const allUrl = "/pages/viewpage.action?pageId=54305546";
const filepath =
  "E:\\space-work\\source-code\\vision-platform-edu-fronts\\src\\assets\\images\\intro\\basic";
const instance = axios.create({
  baseURL: domain,
  timeout: 5000,
  headers: {
    Cookie:
      "confluence.browse.space.cookie=space-blogposts; seraph.confluence=56688641%3A9a6e4325c85ea574682408efae99eba26f456e65; JSESSIONID=F85B5646F1E9F02FDB9CB57C2F6BFF83",
  },
});

let imgIndex = 0;

async function downloadFile(url, filepath, name) {
  if (!fs.existsSync(filepath)) {
    fs.mkdirSync(filepath);
  }
  const mypath = path.resolve(filepath, `${name}.png`);
  const writer = fs.createWriteStream(mypath);
  const response = await instance({
    url,
    method: "GET",
    responseType: "stream",
  });
  response.data.pipe(writer);
  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}
async function buildData() {
  try {
    const res = await instance.get(allUrl);
    const dom = new JSDOM(res.data);
    const doc = dom.window.document;
    var content = doc.getElementById("main-content");

    const data = [];
    for (let item of content.children) {
      const img = item.getElementsByTagName("img");
      const isImg = img.length > 0;
      if (isImg) {
        data.push({ type: "img", imgIndex: imgIndex });
        await downloadFile(img[0].src, filepath, `${imgIndex}`);
        imgIndex = imgIndex + 1;
        continue;
      }
      if (item.tagName.toLocaleLowerCase() === "h1") {
        data.push({ type: "1", text: item.textContent.replace("\n", "") });
        continue;
      }
      if (item.tagName.toLocaleLowerCase() === "h2") {
        data.push({ type: "2", text: item.textContent.replace("\n", "") });
        continue;
      }
      if (item.tagName.toLocaleLowerCase() === "h3") {
        data.push({ type: "3", text: item.textContent.replace("\n", "") });
        continue;
      }
      if (item.tagName.toLocaleLowerCase() === "h4") {
        data.push({ type: "4", text: item.textContent.replace("\n", "") });
        continue;
      }
      if (item.textContent != "\n" && item.textContent != "") {
        data.push({ type: "p", text: item.textContent.replace("\n", "") });
      }
    }

    const s = JSON.stringify(data);
    // console.log();

    fs.writeFileSync("./test.json", s);
  } catch (err) {
    console.log(err);
  }
}

buildData();
